package com.mayikt.jwt;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import sun.misc.BASE64Decoder;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @ClassName Test006
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class Test006 {
    private static final String SIGN_KEY = "mayiktSignKey";

    public static void main(String[] args) throws UnsupportedEncodingException {
        // 手写jwt 封装三个部分 header· 、payload  sign签名值
        /**
         * base64( header· 、payload)
         */
        // 定义header
        JSONObject header = new JSONObject();
        header.put("alg", "HS256");
        //payload
        JSONObject payload = new JSONObject();
        payload.put("phone", "1592*****100");
        String headerEncoded = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String payLoadJsonStr = payload.toJSONString();
        String payloadEncoded = Base64.getEncoder().encodeToString(payLoadJsonStr.getBytes());
        //  sign签名值 实际上就md5
        String sign = DigestUtils.md5Hex(payLoadJsonStr + SIGN_KEY);
        String jwt = headerEncoded + "." + payloadEncoded + "." + sign;
        System.out.println(jwt);

        // 解密
        String payLoadEncode = jwt.split("\\.")[1];
        String payLoadDecoder = new String(Base64.getDecoder().decode(payLoadEncode), "UTF-8");
        String newSign = DigestUtils.md5Hex(payLoadDecoder + SIGN_KEY);
        System.out.println(newSign.equals(jwt.split("\\.")[2]));
    }
}
